from flask import Blueprint, request, render_template, g, redirect, url_for
from .forms import QuestionForm, AnswerForm  # 导入问题，回答表单类
from models import QuestionModel, AnswerModel  # 数据库模型
from exts import db  # 数据库扩展
from decorators import login_required  # 登录校验装饰器

# 创建蓝图（所有路由直接挂在根路径下，比如首页就是/）
bp = Blueprint("qa", __name__, url_prefix='/')


# 首页：显示所有问题
@bp.route('/')
def index():
    # 从数据库按时间倒序获取所有问题
    questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()
    # 渲染模板
    return render_template("index.html", questions=questions)


# 发布问题（需登录）
@bp.route("/qa/publish", methods=["GET", "POST"])
@login_required  # 添加装饰器，必须登录才能访问
def publish_question():
    if request.method == 'GET':  # 访问发布页
        return render_template("publish_question.html")
    else:  # 提交问题表单
        form = QuestionForm(request.form)
        if form.validate():  # 表单验证通过
            title = form.title.data
            content = form.content.data
            # 创建问题对象（关联当前用户g.user）
            question = QuestionModel(title=title, content=content, author=g.user)
            db.session.add(question)  # 添加到数据库
            db.session.commit()
            return redirect("/")
        else:  # 表单验证失败
            print(form.errors)
            return redirect(url_for("qa.publish_question"))  # 返回发布页


# 问题详情页
@bp.route("/qa/detail/<qa_id>")
def qa_detail(qa_id):
    question = QuestionModel.query.get(qa_id)  # 根据ID查询问题
    return render_template("detail.html", question=question)  # 渲染详情页


# 发布回答（需登录）
@bp.route("/answer/publish", methods=["POST"])
@login_required
def publish_answer():
    form = AnswerForm(request.form)
    if form.validate():  # 回答内容验证
        content = form.content.data
        question_id = form.question_id.data
        # 创建回答对象（关联问题ID和当前用户ID）
        answer = AnswerModel(content=content, question_id=question_id, author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for("qa.qa_detail", qa_id=question_id))  # 跳回问题详情页
    else:
        print(form.errors)
        # # 防止表单验证失败时question_id丢失，改用request.form获取
        return redirect(url_for("qa.qa_detail", qa_id=request.form.get("question_id")))


# 搜索功能
@bp.route("/search")
def search():
    # 获取URL中的搜索关键词（如/search?q=Python）
    q = request.args.get("q")
    # 在标题中模糊搜索（contains会生成SQL的LIKE语句）
    questions = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    # 复用首页模板显示结果
    return render_template("index.html", questions=questions)
